package com.cbw.dao.ImpI;

import com.cbw.dao.BaseAdminDao;
import com.cbw.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class BaseAdminDaoImpI implements BaseAdminDao {

    private static PreparedStatement pps=null;
    private static ResultSet resultSet=null;
    private static Connection conn=null;

    //更新管理员登录时间和ip
    private static final String SQL_UPDATE_LOGIN_TIME = "update eadmin set logintime=?,loginip=? where username=?";
    //管理员登录
    private static final String SQL_LOGIN = "select id from eadmin where username=? and password=?";

    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        conn = DruidUtil.getConnection();//1.获取连接
        try {
            pps = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME); //2.预编译sql语句(使用常量)
            pps.setDate(1,new java.sql.Date(date.getTime()));//参数util的date，这里需要转sql的date,外层使用util的date方便
            pps.setString(2,ip); //3.填充参数
            pps.setString(3,username);//4.执行
            pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,pps,null); //5.释放资源
        }
    }

    @Override
    public boolean login(String username, String password) {
        System.out.println("login方法被执行");
        System.out.println("登录的用户名和密码:"+username+" "+password);
        conn = DruidUtil.getConnection();
        try {
            pps = conn.prepareStatement(SQL_LOGIN);
            pps.setString(1,username);
            pps.setString(2,password);
            resultSet = pps.executeQuery();
            return resultSet.next();//根据查询结果，返回true，false(判断第一条记录是否存在)
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,pps,resultSet);
        }
        return false;
    }
}
